import { _decorator, Component, SpriteFrame, Label, v3, Sprite, Node } from "cc";
import ClickDelegate from "../../core/component/ClickDelegate";
import Toast from "../../core/component/Toast";
import { Engine } from "../../core/Engine";
import { uiManager } from "../../core/manager/UIManager";
import Logger from "../../core/utils/Logger";
import { delay, getNumFloor } from "../../core/utils/utils";
import { dataManager } from "../data/DataManager";
import { BELONG_TYPE, BuildInfoData, CityInfoData } from "../data/MapData";
import { DATA_NAME, DATA_OPTION, DATA_PROPERTY, EVENT_NAME, UI_NAME } from "../GameConstant";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = City
 * DateTime = Sun Dec 19 2021 00:33:31 GMT+0800 (中国标准时间)
 * Author = han2007happy
 *
 */

@ccclass("City")
export class City extends Component {
    @property({ type: Sprite, displayName: "形象" })
    cityIcon!: Sprite;

    @property({ type: Node, displayName: "城池状态" })
    statusNode!: Node;

    @property({ type: Node, displayName: "旗帜" })
    flagNode!: Node;

    private id!: string;
    private cityData!: CityInfoData;
    private buildDetail: BuildInfoData | undefined;

    onLoad() {
        this.node.getComponent(ClickDelegate)!.init(this, this.showCityInfo);
        Engine.eventManager.on(EVENT_NAME.BUILDING_ON_CITY, this.buildOnCity, this);
        Engine.eventManager.on(EVENT_NAME.REMOVE_BUILDING_ON_CITY, this.removeBuildOnCity, this);
        Engine.eventManager.on(
            EVENT_NAME.UPDATE_CITY,
            (cityId: string) => {
                if (cityId === this.id) {
                    this.cityData = dataManager.dataMap.getCityDetail(cityId)!;
                    this.updateCityFlag();
                }
            },
            this
        );
        Engine.eventManager.on(
            DATA_OPTION.UPDATE + DATA_NAME.MAP_DATA + DATA_PROPERTY.SOLDIER_KILL,
            () => {
                this.cityData = dataManager.dataMap.getCityDetail(this.id)!;
            },
            this
        );
        Engine.eventManager.on(
            EVENT_NAME.BATTLE_END,
            (isWIn: boolean, targetCityId: string, attackPower: number, defensePower: number) => {
                if (this.cityData.id === targetCityId) {
                    const battleNode = this.statusNode.getChildByName("battle")!;
                    battleNode.active = true;
                    battleNode.getChildByName("power")!.getComponent(Label)!.string = `${getNumFloor(
                        attackPower
                    )} -> ${getNumFloor(defensePower)}`;

                    delay(2).then(() => {
                        battleNode.active = false;
                        if (isWIn) {
                            Toast.showToast("胜利了");
                        } else {
                            Toast.showToast("寡不敌众");
                        }
                    });
                }
            },
            this
        );
    }

    start() {
        // [3]
    }

    setData(cityId: string) {
        this.id = cityId;
        this.cityData = dataManager.dataMap.getCityDetail(cityId)!; // terrianList[cityId];
        const [cityX, cityY] = this.cityData.pos.split("-");
        this.node.name = cityId;
        this.node.position = v3(Number(cityX), Number(cityY), 0);
        this.node.getChildByName("name")!.getComponent(Label)!.string = `${cityId}`;
        this.buildDetail = dataManager.dataMap.getBuildDetail(cityId);

        this.updateCityFlag();
        this.renewCityAvatar();
    }

    // 默认展示地块形象，有建筑展示建筑形象
    renewCityAvatar() {
        let resId = "terrian-" + this.cityData.type;
        if (this.buildDetail) {
            resId = this.buildDetail.res;
        }
        Engine.resManager
            .loadPath<SpriteFrame>("textures/map/" + resId + "/spriteFrame")
            .then((sprFame: SpriteFrame) => {
                this.cityIcon!.spriteFrame = sprFame;
            });
    }

    updateCityFlag() {
        this.flagNode.children.forEach((child) => {
            child.active = false;
        });
        this.flagNode.children[this.cityData.belong].active = true;
    }

    private buildOnCity(cityId: string, buildCfgId: string) {
        if (cityId === this.id) {
            this.buildDetail = dataManager.dataMap.getBuildDetail(cityId);
            this.renewCityAvatar();
        }
    }

    private removeBuildOnCity(cityId: string) {
        if (cityId === this.id) {
            this.buildDetail = undefined;
            this.renewCityAvatar();
        }
    }

    private showCityInfo() {
        if (dataManager.dataMap.readyBattleCity) {
            if (this.id === dataManager.dataMap.readyBattleCity.cityId) {
                Toast.showToast("选择出征城池和目标城池不要是同一个城池");
                return;
            }
            // 等等选择战斗城池
            if (
                this.cityData.belong === BELONG_TYPE.SELF_SIDE &&
                this.cityData.belong === dataManager.dataMap.readyBattleCity.belong
            ) {
                // Toast.showToast("同归属的城池认为派遣兵力合并，否则任务战斗");
                uiManager.show(UI_NAME.DISPATCH_SOLDIER_PANEL, dataManager.dataMap.readyBattleCity.cityId, this.id);
            } else {
                if (this.cityData.belong === BELONG_TYPE.SELF_SIDE) {
                    uiManager.show(UI_NAME.DISPATCH_SOLDIER_PANEL, this.id, dataManager.dataMap.readyBattleCity.cityId);
                } else if (dataManager.dataMap.readyBattleCity.belong === BELONG_TYPE.SELF_SIDE) {
                    uiManager.show(UI_NAME.DISPATCH_SOLDIER_PANEL, dataManager.dataMap.readyBattleCity.cityId, this.id);
                } else {
                    Toast.showToast("选择城池有误");
                }
            }
            return;
        }
        if (!this.buildDetail) {
            uiManager.show(UI_NAME.CITY_INFO_PANEL, this.id);
        } else {
            uiManager.show(UI_NAME.BUILD_INFO_PANEL, this.id);
        }
    }
}
